package conf

import (
	"errors"
	"fmt"
	"gitee.com/whilew/cream/pkg/util/xcodec"
	"io/ioutil"
	"path/filepath"
	"strings"
)

// DataSourceFile defines file scheme
const (
	DataSourceFile = "file"
)

var (
	DefaultConfigFilePath = "config.yaml"
)

/*
	尝试加载配置文件
	resp：是否可以加载、加载是否存在异常
*/
func try_load_file_config(codec string) (bool, error) {
	ok := false
	fmt.Println("开始尝试加载file配置...")
	config_file_path := GetString("config.file.path")
	if config_file_path == "" {
		fmt.Println("未获取到【config.file.path】配置,尝试使用默认配置")
		config_file_path = DefaultConfigFilePath
	} else {
		ok = true
		fmt.Printf("获取到【config.file.path=%s】,开始加载file配置...", config_file_path)
	}

	// 读取file配置
	if err := load_file_config(config_file_path, codec); err != nil {
		return ok, errors.New("加载file配置异常：" + err.Error())
	}
	return ok, nil
}

// 获取配置数据
func load_file_config(config_file_path string, default_config_codec string) error {
	absolutePath, err := filepath.Abs(config_file_path)
	if err != nil {
		return errors.New(fmt.Sprintf("get file config absolute path error. path:%s, err: %v", config_file_path, err))
	}
	fileType := strings.Split(config_file_path, ".")
	var content_codec string
	switch fileType[len(fileType)-1] {
	case "yaml":
		content_codec = xcodec.XcodecYaml
	case "json":
		content_codec = xcodec.XcodecJson
	default:
		content_codec = default_config_codec
		//return errors.New(fmt.Sprintf("no codec adaptate this file type [%s]", config_file_path))
	}

	data, err := read_file_config(absolutePath, content_codec)
	if err != nil {
		return err
	}
	setConfig(data)
	//dir := xfile.CheckAndGetParentDir(absolutePath)
	return nil
}

func read_file_config(path, codec string) (map[string]interface{}, error) {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("read file by absolute path error. absolute_path:%s, err: %v", path, err))
	}
	conf := map[string]interface{}{}
	if err := xcodec.Decode(codec, content, &conf); err != nil {
		return nil, errors.New(fmt.Sprintf("decode file config data failed: %v，codec: %s", err, codec))
	}
	return conf, nil
}
